
package org.itboys.mobile.controller.mobile;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.dto.SundayCommentDto;
import org.itboys.mobile.dto.product.SundayProductBrandDto;
import org.itboys.mobile.dto.product.SundayProductCategoryDto;
import org.itboys.mobile.dto.product.SundayProductDto;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.service.mongo.front.SundayFrontCommentService;
import org.itboys.mobile.service.mongo.front.SundayFrontFootprintService;
import org.itboys.mobile.service.mysql.front.SundayFrontProductBrandService;
import org.itboys.mobile.service.mysql.front.SundayFrontProductCategoryService;
import org.itboys.mobile.service.mysql.front.SundayFrontProductService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.MobileSignUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：圣代_商品_controller_mobile
 *
 */

@Controller
@RequestMapping("/sunday/mobile/product")
public class SundayMobileProductController extends BaseController {

    @Autowired
    private SundayFrontProductCategoryService productCategoryService;
    @Autowired
    private SundayFrontProductService productService;
    @Autowired
    private SundayFrontCommentService commentService;

    @Autowired
    private SundayFrontFootprintService footprintService;
    @Autowired
    private SundayFrontProductBrandService brandService;



    /**
     * 获取商品分类（树形结构）
     *
     * @param request
     * @param response
     * @param categoryId
     */
    @RequestMapping(value = "/category/getTree", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "【手机端】获取商品分类（树形结构,包含一级和二级分类）。")
    public void category_getTree(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required = false, name = "categoryId", value = "一级分类ID。根据此ID，选中对应的一级分类。标识字段：isCheck 0未选择，1已选择") @RequestParam(value = "categoryId", required = false) Long categoryId,

            @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign) {
        try {
            //2018年1月24日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }

            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayProductCategoryDto> result = productCategoryService.getTree(memberId, categoryId);
            ResponseMessage.success(result);
        } catch (Exception e) {
            String msg = "";
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
            } else {
                msg = CommonConstants.ERROMSG;
                logger.info("/sundays/mobile/product/category/getTree-------" + e);
            }
            ResponseMessage.error(CommonConstants.FAIL_CODE, msg);
        }
    }

    /**
     * 获取商品分类（树形结构）
     *
     * @param request
     * @param response
     * @param categoryId
     */
    @RequestMapping(value = "/category/getByParentId", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "【手机端】获取商品二级分类（建议不使用此接口）。")
    public void category_getByParentId(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required = true, name = "categoryId", value = "【参与签名】一级分类ID。") @RequestParam(value = "categoryId", required = true) Long categoryId,
            @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign) {
        try {
            //2018年1月24日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            param.put("categoryId",categoryId);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            List<SundayProductCategoryDto> result = productCategoryService.getByParentId(categoryId);
            ResponseMessage.success(result);
        } catch (Exception e) {
            String msg = "";
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
            } else {
                msg = CommonConstants.ERROMSG;
                logger.info("/sundays/mobile/product/category/getByParentId-------" + e);
            }
            ResponseMessage.error(CommonConstants.FAIL_CODE, msg);
        }
    }

    /**
     * 分页查询商品
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/select", method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value = "【手机端】获取商品列表。分页")
    public void select(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required = false, name = "name", value = "商品名称。模糊查询参数") @RequestParam(value = "name", required = false) String name,
            @ApiParam(required = false, name = "brandId", value = "品牌ID。查询参数。注意搭配type参数。目前只有全球购（海淘）中有此参数") @RequestParam(value = "brandId", required = false) Long brandId,
            @ApiParam(required = false, name = "shopId", value = "商家ID。查询参数") @RequestParam(value = "shopId", required = false) Long shopId,
            @ApiParam(required = false, name = "firstCatId", value = "一级分类ID。只在顶部分类时使用") @RequestParam(value = "firstCatId", required = false) Long firstCatId,

            @ApiParam(required = false, name = "secondCatId", value = "二级分类ID。只在顶部分类进入后，选择对应的二级分类ID") @RequestParam(value = "secondCatId", required = false) Long secondCatId,
            @ApiParam(required = false, name = "type", value = "商品类型。4海淘，5分销，6爱购币，7积分，8秒杀，9拼团，10试用") @RequestParam(value = "type", required = false) Integer type,
            //   @ApiParam(required = false, name = "villageId", value = "小区ID") @RequestParam(value = "villageId", required = false) Long villageId,
            @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
            @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
            @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空。销量：saleNumber,价格：price") @RequestParam(value = "sort", required = false) String sort,
            @ApiParam(required = false, name = "order", value = "排序参数。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
            @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign) {
        try {
            //2018年1月24日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayProductDto> result = productService.selectProduct(request,memberId,shopId, firstCatId,secondCatId, type,brandId);
            ResponseMessage.success(result);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/mobile/product/select----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }
    /**
     * 获取品牌
     * @param request
     * @param response
     */
    @RequestMapping(value = "/brand/getData", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "【微信端】获取品牌列表。不分页")
    public void brand_getData(
            HttpServletRequest request,
            HttpServletResponse response,
            Model model,
            @ApiParam(required = false, name = "firstCatId", value = "一级分类ID。选择一级分类时使用") @RequestParam(value = "firstCatId", required = false) Long firstCatId,
            @ApiParam(required = false, name = "secondCatId", value = "二级分类ID。一级分类进入后，选择对应的二级分类ID") @RequestParam(value = "secondCatId", required = false) Long secondCatId,
            @ApiParam(required = false, name = "name", value = "品牌。模糊查询参数") @RequestParam(value = "name", required = false) String name
    ){
        try{

            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayProductBrandDto> brand = brandService.getBrands(firstCatId,secondCatId,name,null);
            ResponseMessage.success(brand);
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code= CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code= CommonConstants.TOKEN_CODE;
                msg= CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/mobile/product/brand/getData----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
    /**
     * 获取商品评论
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/comment/select", method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value = "【手机端】获取商品评论。分页")
    public void comment_select(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required = true, name = "productId", value = "商品ID。【参与签名】") @RequestParam(value = "productId", required = true) Long productId,
            //   @ApiParam(required = false, name = "villageId", value = "小区ID") @RequestParam(value = "villageId", required = false) Long villageId,
            @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
            @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
            @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空。销量：saleNumber,价格：price") @RequestParam(value = "sort", required = false) String sort,
            @ApiParam(required = false, name = "order", value = "排序参数。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order,
            @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign) {
        try {
            //2018年1月24日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("productId",productId);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayCommentDto> result = commentService.getCommentByPage(request,1,productId);
            ResponseMessage.success(result);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/mobile/product/comment/select----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }
  /*  *//**
     * 获取拼团商品所有拼团组。不分页
     *
     * @param request
     * @param response
     *//*
    @RequestMapping(value = "/team/select", method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value = "【手机端】获取拼团商品所有拼团组。不分页")
    public void team_select(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required = false, name = "productId", value = "商品ID。") @RequestParam(value = "productId", required = false) Long productId,
            @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign) {
        try {
            //2018年1月24日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            List<SundayTeamGroupDto> result = teamGroupService.getGroup(request,productId,null);
            ResponseMessage.success(result);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/mobile/product/team/select----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }*/
    /**
     * 移动端获取-商品-详情
     *
     * @param request
     * @param response
     * @param productId
     */
    @RequestMapping(value = "/detail", method= { RequestMethod.POST,RequestMethod.GET})
    @ApiOperation(value = "【手机端】获取商品详情。如果是拼团商品内含所有拼团组集合")
    public void detail(
            HttpServletRequest request,
            HttpServletResponse response,
            @ApiParam(required = true, name = "productId", value = "商品ID。【参与签名】") @RequestParam(value = "productId", required = true) Long productId,
            @ApiParam(value = "随机数。【参与签名】")@RequestParam(value = "nonce", required = true) String nonce,
            @ApiParam(value = "签名")@RequestParam(value = "sign", required = true) String sign) {
        try {
            //2018年1月24日，新增，验证签名
            Map<String, Object> param =new HashMap<String,Object>();
            param.put("nonce", nonce);
            param.put("sign", sign);
            param.put("productId",productId);
            boolean signSer = MobileSignUtils.signCheck(param, sign);
            if(!signSer){
                logger.warn("签名校验失败");
//                ResponseMessage.error(-1,"签名校验失败");
//                return;
            }
            Long memberId = AccountIdHoldUtils.getMemberId();
            SundayProductDto result = productService.getDetail(memberId, productId);

            //生成足迹
            footprintService.save(memberId,productId);
            ResponseMessage.success(result);
        } catch (Exception e) {
            String msg = CommonConstants.ERROMSG;
            Integer code = CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if (e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")) {
                msg = e.getMessage();
                //token已过期
            } else if (e.getClass().getSimpleName().equalsIgnoreCase("TokenException")) {
                code = CommonConstants.TOKEN_CODE;
                msg = CommonConstants.TOKENMSG;
            } else {
                logger.error("/sunday/mobile/product/findOne----e=" + e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code, msg);
        }
    }

    /**
     * 商品详情HTLM5
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "/desc", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiOperation(value = "获取商品详情。该接口会直接在商品详情中返回，不需要调用")
    public String desc_html5(HttpServletRequest request,
                             Model model,
                             @RequestParam(value = "id", required = true) long id) {
        SundayProduct product = productService.find(id);
        model.addAttribute("product", product);
        return "/sunday/product/desc";
    }


}